package lzzy.com;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TaskThreadDemo {
    public static void main(String[] args) {
//        // Create tasks
//        // 创建任务
//        Runnable printA = new PrintChar('a', 100);
//        Runnable printB = new PrintChar('b', 100);
//        Runnable print100 = new PrintNum(100);
//
//        // Create threads
//        // 创建线程
//        Thread thread1 = new Thread(printA);
//        Thread thread2 = new Thread(printB);
//        Thread thread3 = new Thread(print100);
//
//        // Start threads
//        // 启动线程
//        thread1.start();
//        thread2.start();
//        thread3.start();
        // 创建一个最大包含三个线程的固定线程池
        ExecutorService executor = Executors.newFixedThreadPool(3);
        // 向执行程序提交可运行的任务
        executor.execute(new PrintChar('a',50));
        executor.execute(new PrintChar('b',50));
        executor.execute(new PrintNum(100));
        // 关闭线程池
        executor.shutdown();
    }
}

// The task for printing a specified character in specified times
// 在指定时间打印指定字符的任务
class PrintChar implements Runnable {
    private char charToPrint; // The character to print 要打印的字符
    private int times; // The times to repeat 重复的时间

    /**
     * Construct a task with specified character and number of times to print the character
     * 构造具有指定字符和次数的任务以打印字符
     */
    public PrintChar(char c, int t) {
        charToPrint = c;
        times = t;
    }

    /**
     * Override the run() method to tell the system what the task to perform
     * 重写 run() 方法来告诉系统要执行什么任务
     */
    @Override
    public void run() {
        for (int i = 0; i < times; i++) {
            System.out.print(charToPrint);
        }
    }
}

// The task class for printing number from 1 to n for a given n
// 对于给定的 n 打印从 1 到 n 的数字的任务类
class PrintNum implements Runnable {
    private int lastNum;

    /**
     * Construct a task for printing 1, 2, ... i
     * 构建打印任务
     */
    public PrintNum(int n) {
        lastNum = n;
    }

    /**
     * Tell the thread how to run
     * 告诉线程如何运行
     */
    @Override
    public void run() {
        for (int i = 1; i < lastNum; i++) {
            System.out.print(" " + i);
        }
    }
}